/*
 * Copyright ©2021 su binglun(9085309@qq.com). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *---------------------------------------------------------------------
 *-                                                                   -
 *-           Website : http://phoenix.sunny360.cn/                   -
 *-                                                                   -
 *---------------------------------------------------------------------
 */
package cn.sunny360.core.handler.http;

import cn.sunny360.core.service.DeviceService;
import cn.sunny360.core.utils.Container;
import cn.sunny360.messsage.MsgDevice;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import org.apache.commons.lang3.StringUtils;

public class DeviceHandler extends HttpBaseHandler{
	
	private static final Logger logger = LoggerFactory.getLogger(UserHandler.class);

	private DeviceService deviceService;
	
	public DeviceHandler() {
		this.deviceService = Container.getComponent(DeviceService.class);
	}
	/**
	 * app安装后自动向服务端提交收集的设备信息
	 * @param context
	 */
	public void deviceRegister(RoutingContext context) {
		//接收设备信息
		String contentType = context.request().getHeader("Content-Type");
		if (StringUtils.isNotBlank(contentType) 
				&& contentType.contains("application/octet-stream")) {

			Buffer body = context.getBody();
			MsgDevice device = MsgDevice.newInstance();
			device.parseByteArray(body.getBytes());
			logger.debug(device.toJson());
			//保存设备信息
			Promise<String> promise = Promise.promise();
			deviceService.saveDeviceInfo(new JsonObject(device.toJson()), promise);
			promise.future()
					.onSuccess(token->{
						logger.debug(token);
						okResult(context, "OK", token);
					})
					.onFailure(e->{
						logger.error("注册设备失败",e);
						badResult(context, e);
					});

		} else {
			badResult(context, "请求数据格式错误");
		}
		
	}
}
